﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.StorageClient;

namespace AzureDiagMon.Common.Helpers.Azure
{
    public class AzureStorageContext
    {
        private readonly CloudStorageAccount storageAccount;
        private CloudTableClient cloudTableClient;

        public CloudTableClient CloudTableClient
        {
            get
            {
                if (cloudTableClient == null)
                    cloudTableClient = storageAccount.CreateCloudTableClient();

                return cloudTableClient;
            }
        }

        public AzureStorageContext(string connectionString)
        {
            storageAccount = CloudStorageAccount.Parse(connectionString);
        }

        public AzureStorageContext(string name, string key)
        {
            var connectionString = String.Format("DefaultEndpointsProtocol=https;AccountName={0};AccountKey={1}", name, key);
            storageAccount = CloudStorageAccount.Parse(connectionString);
        }


        public GenericTableServiceContext<T> CreateTableContext<T>(string tableName) where T : TableServiceEntity
        {
            CloudTableClient.CreateTableIfNotExist(tableName);
            return new GenericTableServiceContext<T>(cloudTableClient.GetDataServiceContext(), tableName);
        }

        public IEnumerable<string> ListTables()
        {
            return CloudTableClient.ListTables().ToList();
        }

    }
}
